package com.maimang.platform.manager.factory;

import com.maimang.platform.common.entity.SysApiLog;
import com.maimang.platform.common.entity.SysLoginLog;
import com.maimang.platform.common.entity.SysOperLog;
import com.maimang.platform.common.entity.SysUserOnline;
import com.maimang.platform.common.service.SysApiLogService;
import com.maimang.platform.common.service.SysOperLogService;
import com.maimang.platform.common.service.impl.SysLoginLogServiceImpl;
import com.maimang.platform.common.service.impl.SysUserOnlineServiceImpl;
import com.maimang.platform.common.utils.LogUtils;
import com.maimang.platform.common.utils.ShiroUtils;
import com.maimang.platform.common.utils.http.ServletUtils;
import com.maimang.platform.common.utils.spring.SpringUtils;
import com.maimang.platform.constant.Constants;
import com.maimang.platform.shiro.session.OnlineSession;
import com.maimang.platform.shiro.session.SessionDao;
import com.maimang.platform.tool.ToolAddress;
import eu.bitwalker.useragentutils.UserAgent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.messaging.simp.SimpMessagingTemplate;

import java.util.List;
import java.util.TimerTask;

/**
 * @author Rocky
 * @version 1.0.0
 * @classname AsyncFactory
 * @description 异步工厂
 * @date 2019-04-22 16:06
 * @email jintaozhao@qq.com
 */
public class AsyncFactory {

	private static final Logger sysUserLogger = LoggerFactory.getLogger("sys-user");

	/**
	 * 同步session到数据库
	 *
	 * @param session 在线用户会话
	 * @return 任务task
	 */
	public static TimerTask syncSessionToDb(final OnlineSession session) {
		return new TimerTask() {
			@Override
			public void run() {
				SysUserOnline online = new SysUserOnline();
				online.setSessionId(String.valueOf(session.getId()));
				online.setDeptName(session.getDeptName());
				online.setLoginName(session.getLoginName());
				online.setUserName(session.getUserName());
				online.setStartTimestamp(session.getStartTimestamp());
				online.setLastAccessTime(session.getLastAccessTime());
				online.setExpireTime(session.getTimeout());
				online.setIpaddr(session.getHost());
				online.setLoginLocation(ToolAddress.getRealAddressByIP(session.getHost()));
				online.setBrowser(session.getBrowser());
				online.setOs(session.getOs());
				online.setStatus(session.getStatus());
				SpringUtils.getBean(SysUserOnlineServiceImpl.class).saveOnline(online);
			}
		};
	}

	/**
	 * 操作日志记录
	 *
	 * @param operLog 操作日志信息
	 * @return 任务task
	 */
	public static TimerTask recordOper(final SysOperLog operLog) {
		return new TimerTask() {
			@Override
			public void run() {
				// 远程查询操作地点
				operLog.setOperLocation(ToolAddress.getRealAddressByIP(operLog.getOperIp()));
				SpringUtils.getBean(SysOperLogService.class).insertOperlog(operLog);
			}
		};
	}


	/**
	 * api接口请求日志记录
	 *
	 * @param apiLog 操作日志信息
	 * @return 任务task
	 */
	public static TimerTask recordApiLog(final SysApiLog apiLog) {
		return new TimerTask() {
			@Override
			public void run() {
				// 远程查询操作地点
				apiLog.setUserLocation(ToolAddress.getRealAddressByIP(apiLog.getUserHost()));
				SpringUtils.getBean(SysApiLogService.class).insertSysApiLog(apiLog);
			}
		};
	}

	/**
	 * 向在线用户发送消息
	 *
	 * @param loginNames 接收人列表
	 * @param title
	 * @return
	 */
	public static TimerTask sendNoticeOnLine(String[] loginNames, String title) {
		return new TimerTask() {
			@Override
			public void run() {
//                List<SysUser> sysUserOnlines = SpringUtils.getBean(OnlineSessionDAO.class).listOnlineUser();
				List<String> loginNameOnlines = SpringUtils.getBean(SessionDao.class).listOnlineUser();
				SimpMessagingTemplate template = SpringUtils.getBean(SimpMessagingTemplate.class);
				for (String loginName : loginNames) {
					if (loginNameOnlines.contains(loginName)) {
						template.convertAndSendToUser(loginName, "/queue/notifications", "新消息：" + title);
					}
				}
                /*for (SysUser sysUser: sysUserOnlines) {
                    for (Long userId:userIdList) {
                        if (userId.equals(sysUser.getUserId())) {
                            template.convertAndSendToUser(sysUser.toString(),"/queue/notifications","新消息：" + title);
                        }
                    }
                }*/
			}
		};

	}

	/**
	 * 记录登录信息
	 *
	 * @param username 用户名
	 * @param status   状态
	 * @param message  消息
	 * @param args     列表
	 * @return 任务task
	 */
	public static TimerTask recordLoginLog(final String username, final String status, final String message, final Object... args) {
		final UserAgent userAgent = UserAgent.parseUserAgentString(ServletUtils.getRequest().getHeader("User-Agent"));
		final String ip = ShiroUtils.getIp();
		return new TimerTask() {
			@Override
			public void run() {
				StringBuilder s = new StringBuilder();
				s.append(LogUtils.getBlock(ip));
				s.append(ToolAddress.getRealAddressByIP(ip));
				s.append(LogUtils.getBlock(username));
				s.append(LogUtils.getBlock(status));
				s.append(LogUtils.getBlock(message));
				// 打印信息到日志
				sysUserLogger.info(s.toString(), args);
				// 获取客户端操作系统
				String os = userAgent.getOperatingSystem().getName();
				// 获取客户端浏览器
				String browser = userAgent.getBrowser().getName();
				// 封装对象
				SysLoginLog loginLog = new SysLoginLog();
				loginLog.setLoginName(username);
				loginLog.setIpaddr(ip);
				loginLog.setLoginLocation(ToolAddress.getRealAddressByIP(ip));
				loginLog.setBrowser(browser);
				loginLog.setOs(os);
				loginLog.setMsg(message);
				// 日志状态
				if (Constants.LOGIN_SUCCESS.equals(status) || Constants.LOGOUT.equals(status)) {
					loginLog.setStatus(Constants.SUCCESS);
				} else if (Constants.LOGIN_FAIL.equals(status)) {
					loginLog.setStatus(Constants.FAIL);
				}
				// 插入数据
				SpringUtils.getBean(SysLoginLogServiceImpl.class).insertLoginLog(loginLog);
			}
		};
	}
}
